import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import { Reply, AtSomeone } from 'weaver-mobile-page';
import { Tools } from 'weaver-mobile';
import {Icon, Toast} from 'weaver-mobile';
import $ from 'jquery';
import * as EmSDK from "../../util/emSDK";
const getLabel = Tools.getLabel;
@withRouter
@observer
export default class Demo extends Component {
  componentDidMount() {
    const { store:{ setState }} = this.props;
    setState({signReplyVisible: this.setDetailReplyVisible})
  }
  setDetailReplyVisible = (val) => {
    const replyRef = this.replyRef; // 避免某一瞬间找不到this.replyRef
    if (replyRef) {
      replyRef.setVisible(val, () => {
        if(val){//防止focus的时候，因为获取焦点而自动显示
          replyRef.getInputFocus('last');
        }
      });
    } else {
      window.setTimeout(()=>{
        this.setDetailReplyVisible();
      },0)
    }
  }
  hiddenSignPanel = () => {
    const { setState, signReplyVisible, onMaskClick} = this.props.store;
    signReplyVisible(false);
    setState({showReply: false, replyType: '', placeholderValue: getLabel('512567', '交流内容...')});
    EmSDK.controlBottomBtn('/req');
    $('.wm-reply-panel').css('display', 'none');
    onMaskClick();
  }
  onSubmit = (data) => {
    const { publishCommunicate, saveComment, replyType, setState } = this.props.store;
    let str = '';
    if(data.text != '') {
      str = data.text.replace(/<\/?[^>]*>/g, '');
      str = str.replace(/[\u200B-\u200D\uFEFF]/g, "");
      str = str.replace(/\n/g,'');
      str = str.replace("&#8203;", "").replace(/&nbsp;/g, '');
      str = str.trim();
    } 
    if(str === "" || str === "<p><br></p>") {
      Toast.info(getLabel('382648', "请输入交流内容"), 1);
      return
    }
    replyType == '' && publishCommunicate(data);
    replyType == 'comment' && saveComment(data); 
    setState({showReply: false, replyType: '', placeholderValue: getLabel('512567', '交流内容...')})

  }
   //获取签字意见的文本内容
   contentUtil = (str) => {
    const { store: {setReplyMark}} = this.props;
    let remarkStr =  '<div class="wrap_box">'+ str +'</div>';
    let remarkElement = $(remarkStr);
    remarkElement.children().filter(".container_form_wrap") 
      && remarkElement.children().filter(".container_form_wrap").remove();
    remarkElement.children().filter("span:not(#wea_rich_text_default_font)") 
      && remarkElement.children().filter('span:not(#wea_rich_text_default_font)').remove();
    let newStr = remarkElement.html(); //还原成字符串
    newStr = this.imgWrapDiv(newStr);
    setReplyMark(newStr);
    let pic = `[${getLabel(528760 , '图片')}]`;
    str = newStr.replace(/<img.*?>/g, pic);
    str = str.replace(/<[^>]*>|<\/[^>]*>/gm, "")
    str = str.replace(/\r|\n|\\s/gm, "");
    str = `<div class='remark-quote'>${str}</div>`;
    return str;
  }   

  //给来自移动端的图片外层包裹<div>，解决PC端显示正常的问题。
  imgWrapDiv(srcHtml__) {
    if (srcHtml__.indexOf("img") > -1 || srcHtml__.indexOf("IMG") > -1) {
        var firstnum = srcHtml__.indexOf("<img");
        if (firstnum == -1) {
            firstnum = srcHtml__.indexOf("<img");
        }
        var begin_srcHtml = srcHtml__.substring(0, firstnum);
        var end_srcHtml = "";
        var cycleString = srcHtml__.substring(firstnum);
        while (cycleString.indexOf("<img") > -1 || cycleString.indexOf("<IMG") > -1) {
          var b = cycleString.indexOf("<img");
          if (b == -1) {
              b = cycleString.indexOf("<IMG");
          }
          begin_srcHtml += cycleString.substring(0, b);
          cycleString = cycleString.substring(b);
          var imgString = "";
          var n = cycleString.indexOf(">");
          imgString = cycleString.substring(0, n);
          begin_srcHtml += "<div> " + imgString + "/> </div>";
          cycleString = cycleString.substring(n + 1);
          end_srcHtml = cycleString;
        }
        begin_srcHtml += end_srcHtml; 
        srcHtml__ = begin_srcHtml;
    }
    return srcHtml__;  
  }

  renderAt = (item) => {
    const { history, store: {reqOperators = []}} = this.props;
    let atUserStore = new AtSomeone.Store({route:'/req',id:'remarkat'});
    const template2 = {
      default: {
          theme: 'col2_row2',
          dataKeys: ['data', 'jobtitlename', 'subcompanyname', 'departmentname'],
      },
    };
    return (
      <div className={`communicate-atSome`} 
           onClick={() => {history.push(atUserStore.path)}}
      >
        {item}
          <AtSomeone
            datas={toJS(reqOperators)}
            template={template2}
            store={atUserStore}
            onOk={this.setContentValue}
            imgSrcDataKey={'icon'}
            nameDataKey={'data'}
        />
      </div>
    )
  }

  setContentValue = (datas) => {
    const {
      replyType, 
      replyComment, 
      replyStoreMap, 
      communicateReplyStore, 
      communicateReplyStoreMap,
      replyInfo:{logid}
    } = this.props.store;
    let replyStore = null;
    if(replyType == '') {
      if(communicateReplyStoreMap.has(parseInt(logid))) {
        replyStore = communicateReplyStoreMap.get(parseInt(logid));
      } else {
        replyStore = communicateReplyStore; //评论签字意见
      }
    } else if( replyType == 'comment') { //回复签字意见
      replyStore =  replyStoreMap[replyComment.replyId];
    }
    const replyRef = this.replyRef;
    if (datas && datas.length > 0) {
      let html = '';
      datas.map((item) => {
        const value = `@${item.data.replace(/\(/g,'（').replace(/\)/g,'）')}`;
        html += `<a contenteditable="false" atsome="@${item.id}" atsome-uid="${item.id}" atsome-name="${item.data.replace(/\(/g,'（').replace(/\)/g,'）')}" target="_blank" style="cursor:pointer;text-decoration:none !important;color:#2777c1!important;" href="javascript:void(0)">${value}</a>&nbsp;`;
      });
      replyRef.replyRef.changeTextValue(html);
      replyStore.setState({
        atLists: [
          ...toJS(replyStore.atLists),
          ...datas
        ]
      })
    }
  }


  getHeader = () => {
    const { replyInfo = {}} = this.props.store;
    const {  
      displayname = '', 
      displaydepname = '', 
      log_agentorbyagentid = '', 
      log_operatedate= '', 
      log_operatetime = '', 
      log_nodename = '', 
      operationname = '', 
      log_remarkHtml = '' 
    } = replyInfo;
    let dom = (
      <div className={'sign-reply-panel'} ref = {ref => this.signReplyPanel = ref}>
          <div className={'needWrap'} >
            {<div className={'quote-top-words'}>
              <div className={'top-panel'}>
                <div className={'content-top-quote'}> 
                  <span className={'wfComu-reply-user'}>
                    <span className='quote-span'>{getLabel('385534', "回复")}</span> 
                    <a href={`javaScript:openhrm(${log_agentorbyagentid});`}  style={{marginRight: '5px'}} onClick={window.pointerXY}>{displayname}</a>
                    <span className={'reply-span reply-department'}>{displaydepname}</span>
                    <span className={'reply-span reply-date'}>{log_operatedate}</span>
                    <span className={'reply-span reply-time'}>{log_operatetime}</span>
                    <span className={'reply-span right-words'}>{'[' + log_nodename + '/' + operationname + ']'}</span>
                  </span>
                  <Icon type={'cross'} size={'xs'} onClick={this.hiddenSignPanel}/>
              </div>
              <div className={'reply-content'}>
                <div className={'wea-cl-content'}  dangerouslySetInnerHTML={{ __html: this.contentUtil(log_remarkHtml)}}></div>
              </div>
            </div>    
          </div>}
        </div>       
      </div>
    )
    return dom;
  }
  render() {
    const { 
      hasLoad, 
      showReply, 
      replyType, 
      replyComment, 
      replyStoreMap, 
      communicateReplyStore, 
      communicateReplyStoreMap,
      placeholderValue,
      leftConfig,
      replyInfo: {logid}
    } = this.props.store;
    let replyStore = null;
    if(replyType == '') {
      if(communicateReplyStoreMap.has(parseInt(logid))) {
        replyStore = communicateReplyStoreMap.get(parseInt(logid));
      } else {
        replyStore = communicateReplyStore; //评论签字意见
      }
    } else if( replyType == 'comment') { //回复签字意见
      replyStore =  replyStoreMap[replyComment.replyId];
    }
    return (
      <div className='reply-div'>
        {showReply && this.getHeader()}
        {
          hasLoad && <Reply
            wrappedComponentRef={ref => this.replyRef = ref} 
            store={replyStore}
            leftConfig={leftConfig}
            visible={false}
            placeholder={placeholderValue}
            onSubmitButtonClick={this.onSubmit}
            onMaskClick={this.hiddenSignPanel}
            renderAt={this.renderAt}
          />
        }
      </div>
    );
  }
}

